package proj2501.simple_module;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import proj2501.util.UU;

class P010Image extends JPanel {
	private BufferedImage bi;
	public P010Image() {
		String[] writerFormatNames = ImageIO.getWriterFormatNames();
		System.out.println("ImageIO.getWriterFormatNames(): ");
		for (int i = 0; i < writerFormatNames.length; i++) {
			System.out.println(UU.getIndent4() + "[" + i + "]: " + writerFormatNames[i]);
		}
		
		String[] readerFormatNames = ImageIO.getReaderFormatNames();
		System.out.println("ImageIO.getReaderFormatNames(): ");
		for (int i = 0; i < readerFormatNames.length; i++) {
			System.out.println(UU.getIndent4() + "[" + i + "]: " + readerFormatNames[i]);
		}
		
		String pngExtension = "png";
		if(! Arrays.asList(writerFormatNames).contains(pngExtension)) {
			throw new RuntimeException();
		}
		if(! Arrays.asList(readerFormatNames).contains(pngExtension)) {
			throw new RuntimeException();
		}
		
		bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
		Graphics g = bi.getGraphics();
		g.setColor(Color.RED);
		g.drawOval(0, 0, 100, 100);
		g.dispose();
		File file = new File("image01." + pngExtension);
		try {
			System.out.println("Writing a file.");
			ImageIO.write(bi, pngExtension, file);
		} catch (IOException e) {
			throw new RuntimeException();
		}
		System.out.println("File Size: " + file.length() + " byte(s).");
		try {
			System.out.println("Reading a file.");
			bi = ImageIO.read(file);
		} catch (IOException e) {
			throw new RuntimeException();
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			System.out.println("Writing a file.");
			ImageIO.write(bi, pngExtension, baos);
		} catch (IOException e) {
			throw new RuntimeException();
		}
		System.out.println(baos.size());
		System.out.println("Deleting a file.");
		file.delete();
	}
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(bi, 0, 0, null);
	}
}
